<template>

  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="视频路径" prop="video">
        <el-input
          v-model="queryParams.video"
          placeholder="请输入视频路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['river_view:river_view:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['river_view:river_view:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['river_view:river_view:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['river_view:river_view:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="river_viewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="视频" align="center" prop="video" >
      <template slot-scope="scope">
        <video :src="scope.row.video" :width="150" :height="100" @click="playVideo(scope.row.video)" style="cursor: pointer;"/>
      </template>
      </el-table-column>>
      <el-table-column label="封面" align="center" prop="cover_img" >
      <template slot-scope="scope">
        <image-preview :src="scope.row.cover_img" :width="150" :height="100"/>
      </template>
        </el-table-column >
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['river_view:river_view:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['river_view:river_view:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改river_view对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="id" prop="id">
          <el-input v-model="form.id" placeholder="请输入id" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="视频路径" prop="video">
          <input type="file" @change="handleFileUpload" ref="videoInput">
          <div v-if="originalVideoPath">当前视频路径：{{ originalVideoPath }}</div>
          <div v-if="isFileSelected">已选文件：{{ form.video.name }}</div>
        </el-form-item>

        <el-form-item label="封面路径" prop="cover_img">
          <input type="file" @change="handleImgFileUpload" ref="coverImgInput">
          <div v-if="originalCoverImgPath">当前封面路径：{{ originalCoverImgPath }}</div>
          <div v-if="isImgFileSelected">已选文件：{{ form.cover_img.name }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 进度条弹窗 -->
  <el-dialog
    :visible.sync="progressVisible"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="400px"
    center
  >
    <div style="text-align: center; padding: 20px;">
      <p style="margin-bottom: 15px; font-size: 16px;">正在提交数据，请稍候...</p>
      <el-progress
        :percentage="progressPercent"
        :format="() => `${progressPercent}%`"
        status="success"
        style="margin: 0 auto 10px;"
      />
      <p v-if="progressPercent < 100" style="color: #999; font-size: 13px;">
        数据提交中，请勿关闭窗口
      </p>
      <p v-else style="color: #67C23A; font-size: 13px;">
        提交完成
      </p>
    </div>
  </el-dialog>

  </div>
</template>

<script>
import { listRiver_view, getRiver_view, delRiver_view, addRiver_view, updateRiver_view } from "@/api/river_view/river_view";

export default {
  name: "River_view",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // river_view表格数据
      river_viewList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      isEdit: false,
      originalVideoPath: '',   // 原始视频路径
      originalCoverImgPath: '',// 原始封面路径

      showProgressBar: false,
      progressPercent: 0,
      debug: '',// 新增
      progressVisible: false // 控制进度条弹窗显示
    };
  },
  created() {
    this.getList();
  },

  computed: {
    isFileSelected() {
      return this.form.video instanceof File;
    },
    isImgFileSelected() {
      return this.form.cover_img instanceof File;
    }
  },

  methods: {
    handleFileUpload(event){
      const file = event.target.files[0];
      this.form.video = file;
    },
    handleImgFileUpload(event){
      const file = event.target.files[0];
      this.form.cover_img = file;
    },
    /** 查询river_view列表 */
    getList() {
      this.loading = true;
      listRiver_view(this.queryParams).then(response => {
        this.river_viewList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      //重置文件输入控件
      this.$refs.videoInput.value = '';
      this.$refs.coverImgInput.value = '';
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        video: null,
        cover_img: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.originalVideoPath='';   // 原始视频路径
      this.originalCoverImgPath=''; // 原始封面路径
      this.isEdit =false;
      this.open = true;
      this.title = "添加river_view";
      // 手动清空文件输入框（DOM 层面）
      if (this.$refs.videoInput) {
        this.$refs.videoInput.value = '';
      }
      if (this.$refs.coverImgInput) {
        this.$refs.coverImgInput.value = '';
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit =true;
      const id = row.id || this.ids
      getRiver_view(id).then(response => {
        // 保存原始路径
        const data = response.data;
        this.originalVideoPath = data.video || '';
        this.originalCoverImgPath = data.cover_img || '';

        this.form = response.data;
        this.open = true;
        this.title = "修改river_view";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // 校验：如果只有视频、没有封面 → 阻止提交
        const hasNewVideo = this.form.video instanceof File;
        const hasNewCover = this.form.cover_img instanceof File;

        if (hasNewVideo && !hasNewCover) {
          this.$modal.msgError("请上传封面图片");
          return;
        }

        // 判断是否需要进入进度条流程（只要有文件上传就走进度条）
        const mustUseProgressBar = hasNewVideo || hasNewCover;

        // ====== 如果不需要进度条（即只改文本）→ 快速提交 ======
        if (!mustUseProgressBar) {
          const simpleFormData = new FormData();
          if (this.form.id != null) simpleFormData.append("id", this.form.id);
          if (this.form.name != null) simpleFormData.append("name", this.form.name);

          const apiFn = this.isEdit ? updateRiver_view : addRiver_view;

          this.open = false;

          apiFn(simpleFormData)
            .then(() => {
              this.getList();
              this.$modal.msgSuccess(this.isEdit ? "修改成功" : "新增成功");
            })
            .catch(err => {
              this.$modal.msgError("提交失败：" + err.message);
              this.open = false;
            });

          return;
        }

        // ====== 有文件上传 → 进入进度条 + 轮询检测 ======

        const formData = new FormData();
        formData.append("id", this.form.id);
        if (this.form.name) formData.append("name", this.form.name);
        if (hasNewVideo) formData.append("video", this.form.video);
        if (hasNewCover) formData.append("cover_img", this.form.cover_img);

        // 关闭弹窗，显示进度条
        this.open = false;
        this.progressVisible = true;
        this.progressPercent = 0;

        const apiFn = this.isEdit ? updateRiver_view : addRiver_view;

        apiFn(formData).then(res => {
          console.log('提交完成');

          let interval = null;

          // 启动进度条动画
          const startProgressBar = () => {
            this.progressPercent = 0;

            interval = setInterval(() => {
              if (this.progressPercent < 90) {
                this.progressPercent += 5;
                if (this.progressPercent > 90) this.progressPercent = 90;
              } else if (this.progressPercent < 99) {
                this.progressPercent += 1; // 每次加 1%
              } else {
                // 到达 99%，开始波动动画
                const fluctuation = Math.random() > 0.5 ? 1 : -1;
                this.progressPercent = Math.min(99, Math.max(95, this.progressPercent + fluctuation));
              }
            }, this.progressPercent < 90 ? 500 : 1000); // 不同阶段不同间隔
          };

          startProgressBar();

          // 新增模式：使用 this.form.id 轮询判断上传完成
          if (!this.isEdit) {
            const newId = this.form.id;
            const hasNewVideo = this.form.video instanceof File;
            const hasNewCover = this.form.cover_img instanceof File;

            let attempt = 0;
            const maxAttempts = 30;

            const polling = setInterval(() => {
              attempt++;
              getRiver_view(newId).then(res => {
                if (!res || !res.data) {
                  console.warn("获取数据失败");
                  return;
                }

                const data = res.data;

                // 判断字段是否非空
                const videoNotEmpty = data.video && data.video.trim() !== '';
                const coverNotEmpty = data.cover_img && data.cover_img.trim() !== '';

                let uploadCompleted = false;

                // 根据上传类型判断是否完成
                if (hasNewVideo && hasNewCover) {
                  uploadCompleted = videoNotEmpty && coverNotEmpty;
                } else if (hasNewVideo) {
                  uploadCompleted = videoNotEmpty;
                } else if (hasNewCover) {
                  uploadCompleted = coverNotEmpty;
                }

                if (uploadCompleted) {
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                    this.$modal.msgSuccess("新增成功");
                  }, 300);
                }
              }).catch(err => {
                console.error('查询失败:', err);
              });

              // 超时控制
              if (attempt > maxAttempts) {
                clearInterval(interval);
                clearInterval(polling);
                this.progressPercent = 100;

                setTimeout(() => {
                  this.progressVisible = false;
                  this.getList();
                  this.$modal.msgWarning("超时，请稍后刷新页面确认状态");
                }, 300);
              }
            }, 2000);
          }

          // 修改模式：轮询判断视频和封面是否变化
          if (this.isEdit) {
            const id = this.form.id;
            const originalVideoPath = this.originalVideoPath;
            const originalCoverPath = this.originalCoverImgPath;

            let attempt = 0;
            const maxAttempts = 30;
            const polling = setInterval(() => {
              attempt++;
              getRiver_view(id).then(res => {
                if (!res || !res.data) {
                  console.warn("获取数据失败，接口返回为空");
                  this.$modal.msgError("获取数据失败，请刷新页面重试");
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                  }, 300);
                  return;
                }

                const data = res.data;
                const currentVideoPath = data.video || '';
                const currentCoverPath = data.cover_img || '';

                const hasNewVideo = this.form.video instanceof File;
                const hasNewCover = this.form.cover_img instanceof File;

                // 判断当前字段是否已更新
                const videoUpdated = currentVideoPath !== originalVideoPath;
                const coverUpdated = currentCoverPath !== originalCoverPath;

                // 根据上传类型决定完成条件
                if (
                  (hasNewVideo && hasNewCover && videoUpdated && coverUpdated) ||
                  (hasNewVideo && !hasNewCover && videoUpdated) ||
                  (!hasNewVideo && hasNewCover && coverUpdated)
                ) {
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                    this.$modal.msgSuccess("修改成功");
                  }, 300);
                }
              }).catch(err => {
                console.error('查询失败:', err);
                this.$modal.msgError("查询失败：" + err.message);
                clearInterval(interval);
                clearInterval(polling);
                this.progressPercent = 100;

                setTimeout(() => {
                  this.progressVisible = false;
                  this.getList();
                }, 300);
              });

              // 超时控制
              if (attempt > maxAttempts) {
                clearInterval(interval);
                clearInterval(polling);
                this.progressPercent = 100;

                setTimeout(() => {
                  this.progressVisible = false;
                  this.getList();
                  this.$modal.msgWarning("超时,后台仍在上传处理中,请稍后刷新");
                }, 300);
              }
            }, 2000);
          }

        }).catch(err => {
          console.error('提交失败:', err);
          this.$modal.msgError("提交失败：" + (err.message || "网络错误"));
          this.progressVisible = false;
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除river_view编号为"' + ids + '"的数据项？').then(function() {
        return delRiver_view(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('river_view/river_view/export', {
        ...this.queryParams
      }, `river_view_${new Date().getTime()}.xlsx`)
    },
    /** 播放视频 */
    playVideo(videoUrl) {
      // 创建一个模态框来播放视频
      const videoHtml = `<video id="videoPlayer" src="${videoUrl}" controls style="max-width: 100%; max-height: 80vh; width: 100%;"></video>`;
      
      this.$alert(videoHtml, '视频播放', {
        dangerouslyUseHTMLString: true,
        showCancelButton: false,
        showConfirmButton: true,
        confirmButtonText: '关闭',
        closeOnClickModal: true,
        customClass: 'video-modal',
        callback: action => {
          // 关闭模态框时停止视频播放
          const videoPlayer = document.getElementById('videoPlayer');
          if (videoPlayer) {
            videoPlayer.pause();
            videoPlayer.currentTime = 0;
          }
        },
        beforeClose: (action, instance, done) => {
          // 无论哪种方式关闭模态框都停止视频播放
          const videoPlayer = document.getElementById('videoPlayer');
          if (videoPlayer) {
            videoPlayer.pause();
            videoPlayer.currentTime = 0;
          }
          done();
        }
      });
    }
  }
};
</script>
